package com.xish.util.qiniu;

import com.qiniu.util.Auth;
import com.xish.spring.env.Env;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class ImageService {

    @Autowired
    private Env env;

    private String urlPublic;
    private String urlPrivate;
    private String accessKey;
    private String secretKey;

    @PostConstruct
    public void init() {
        urlPublic = env.get("qiniu.url.public");
        urlPrivate = env.get("qiniu.url.private");
        accessKey = env.get("qiniu.accessKey");
        secretKey = env.get("qiniu.secretKey");
    }

    public String getImageUrl(Image image) {
        //todo:
        StringBuilder builder = new StringBuilder();
        if (image.isPublic()) {
            builder.append(urlPublic);
        } else {
            builder.append(urlPrivate);
        }

        builder.append('/')
                .append(image.getImageType().value())
                .append(image.getUrlSegment());

        if ((image.getImageSpec() != null) && !image.getImageSpec().isEmpty()) {
            builder.append(image.getImageSpec());
        }

        String url = builder.toString();

        if (image.isPublic()) {
            return url;
        } else {
            Auth auth = Auth.create(accessKey, secretKey);
            return auth.privateDownloadUrl(url);
        }
    }

}
